package com.sykj.seaflow.warm.core.condition;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.sykj.seaflow.warm.core.constant.FlowConstant;
import org.dromara.warm.flow.core.condition.ConditionStrategy;
import org.dromara.warm.flow.core.constant.FlowCons;
import org.dromara.warm.flow.core.utils.ExpressionUtil;

import java.util.Map;

public class ConditionStrategySimpleAnd implements ConditionStrategy {

    @Override
    public String getType() {
        return FlowCons.splitAt + "simple_and" + FlowCons.splitAt;
    }

    /**
     *  重写eval  实现一组表达式的解析
     * @param expression @@eq@@|flag@@eq@@4
     * @param variable
     * @return
     */
    @Override
    public Boolean eval(String expression, Map<String, Object> variable) {
        // 如果前面的通过， 这里就不满足了
        if((boolean) variable.getOrDefault(FlowConstant.SERIAL_NODE_BEFORE_COMPLETED, false)){
            return false;
        }

        Map<String, Object> formVar = (Map<String, Object>) variable.get("formData");
        JSONArray array = JSONUtil.parseArray(expression);
        for (int i = 0; i < array.size(); i++) {
            String key = array.getJSONObject(i).getStr("key");
            String cond = array.getJSONObject(i).getStr("cond");
            String v = array.getJSONObject(i).getStr("value");
//            @@eq@@|flag@@eq@@4
            String type = FlowCons.splitAt + cond + FlowCons.splitAt + "|"
                    + key + FlowCons.splitAt + cond +FlowCons.splitAt + v;
            for(String s : formVar.keySet()){
                Object o = formVar.get(s);
                // 判断
                if(o instanceof  Integer || o instanceof  Long){
                    formVar.put(s, String.valueOf(o));
                }
            }

            if(!ExpressionUtil.evalCondition(type, formVar)){
                return false;
            }
        }
        variable.put(FlowConstant.SERIAL_NODE_BEFORE_COMPLETED, true);
        return true;

    }

}
